package com.cavasmonitor;

import com.cavasmonitor.db.CavasDao;
import com.cavasmonitor.db.LoadData;
import com.cavasmonitor.to.UsuarioTo;
import com.cavasmonitor.util.Session;
import com.cavasmonitor.util.TemperaturesUpdater;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		(new LoadData()).run(this);
		@SuppressWarnings("unused")
		TemperaturesUpdater timer = new TemperaturesUpdater(MainActivity.this);
				

		Button btn = (Button) findViewById(R.id.btnEnter);

		btn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				String user = ((EditText) findViewById(R.id.inputUser))
						.getText().toString().trim();
				String pass = ((EditText) findViewById(R.id.inputPass))
						.getText().toString().trim();

				if (user.length() == 0) {
					new AlertDialog.Builder(MainActivity.this)
							.setTitle(R.string.msg_atencion)
							.setMessage(R.string.msg_usuario_rq)
							.setNeutralButton(R.string.msg_aceptar, null)
							.show();
				} else if (pass.length() == 0) {
					new AlertDialog.Builder(MainActivity.this)
							.setTitle(R.string.msg_atencion)
							.setMessage(R.string.msg_pass_rq)
							.setNeutralButton(R.string.msg_aceptar, null)
							.show();
				} else {

					CavasDao dao = new CavasDao(MainActivity.this);
					dao.open();

					UsuarioTo usuario = dao.getUsuario(user);

					
					dao.close();
					
					if (usuario == null) {
						new AlertDialog.Builder(MainActivity.this)
								.setTitle(R.string.msg_atencion)
								.setMessage(R.string.msg_login_error)
								.setNeutralButton(R.string.msg_aceptar, null)
								.show();
					} else if (!usuario.getPass().equalsIgnoreCase(pass)) {
						new AlertDialog.Builder(MainActivity.this)
								.setTitle(R.string.msg_atencion)
								.setMessage(R.string.msg_login_error)
								.setNeutralButton(R.string.msg_aceptar, null)
								.show();
					} else {
						
						Session.usuario = usuario;
						
						Intent i = new Intent(MainActivity.this,
								OpcionesActivity.class);
						startActivityForResult(i, 1);
					}				
				}
			}
		});

	}
}
